import { PlusOutlined } from '@ant-design/icons';
import { Space,Button, Divider, message,Modal } from 'antd';
import React, { useState, useRef } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import ConfigForm from './components/ConfigForm';
import { ExclamationCircleOutlined } from '@ant-design/icons';
const { confirm } = Modal;
import { rolePage, updateRole, addRole, removeRole, queryRoleModule ,batchRemoveRole} from  '@/services/role';
import { countByRole} from  '@/services/user';


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addRole(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateRole(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (record: API.RoleItem) => {
  const hide = message.loading('正在删除');
 
  try {
    let count=  await countByRole({roleId:record.roleId});
  
    if(count>0){
      hide();
      message.error('当前角色下有用户，请先移除该角色下的用户');
      return false;
    }
    await removeRole({roleId:record.roleId});
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [configModalVisible, handleConfigModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [roleModule, setRoleModule] = useState<string[]>();
  const [roleId, setRoleId] = useState<number>();
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '名称',
      dataIndex: 'roleName',
      width: 300,
    },
    {
      title: '描述',
      dataIndex: 'roleDescription',
      width: 300,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'roleIsdisable',
      hideInSearch: true,
      valueEnum: {
        0: { text: '启用', status: 'Success' },
        1: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={async () => {
              setRoleId(record.roleId);
              const roleModule = await queryRoleModule({ roleId: record.roleId });
              if(roleModule){
                setRoleModule(roleModule);
                handleConfigModalVisible(true);
              }
            }}
          >
            权限
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
              let result=  await handleRemove(record);
              if(result){
                actionRef.current?.reload();
              }
              
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchRemoveRole({ ids: selectedRowKeys.join(',')});
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };


  return (
    <>
      <ProTable
        headerTitle=""
        rowKey="roleId"
        actionRef={actionRef}
     
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        options={false}
        request={(params) => rolePage(params)}
        columns={columns}
        // rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        rowSelection={false}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
           
            </Space>
          );
        }}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      />
      <ConfigForm
        onOk={() => {
          handleConfigModalVisible(false);
          setRoleModule([]);
        }}
        onCancel={() => {
          handleConfigModalVisible(false);
          setRoleModule([]);
        }}
        modalVisible={configModalVisible}
        defaultChecked={roleModule}
        changeRoleModule={setRoleModule}
        roleId={roleId}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default TableList;
